package ae.pcfc.etks.online.web.controller.register;

/* $Id: RecallPinController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * April 11, 2011 	Neha_Chauhan 	        Created
 *
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;

import ae.pcfc.etks.online.common.ConstantsCommon;
import ae.pcfc.etks.online.common.delegate.ClientRegistrationDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.delegate.UtilityDelegate;
import ae.pcfc.etks.online.common.vo.ClientEmailVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.LicIssueAuthVO;
import ae.pcfc.etks.online.common.vo.SearchCriteriaCompanyVO;
import ae.pcfc.etks.online.common.vo.TrakheesIdAndPINVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.ClientPasswordLogin;
import ae.pcfc.etks.online.web.model.ClientRecallPinLogin;

/**
 * Controller that handles all {@link RecallPinController}-related requests,
 * i.e.: all requests for /client/register/recallpin/*
 * 
 * @author Neha Chauhan
 */

@Controller
@RequestMapping(ViewPath.RECALLPIN)
public class RecallPinController extends BaseController{

	private ClientRegistrationDelegate clientRegistrationDelegate;
  
	@Resource(name="clientRegistrationDelegate")
	public void setClientRegistrationDelegate(
			ClientRegistrationDelegate clientRegistrationDelegate) {
		this.clientRegistrationDelegate = clientRegistrationDelegate;
	}
	
	private UserDelegate userDelegate;

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private UtilityDelegate utilityDelegate;
	
	@Resource(name = "utilityDelegate")
	public void setUtilityDelegate(UtilityDelegate utilityDelegate) {
	    this.utilityDelegate = utilityDelegate;
	}


	@ModelAttribute(ConstantsAdmin.NON_CLIENT_COMPANY_REGISTRATION_CLIENT_LICISSUEAUTHORITY_LIST_REQUEST_MODEL_KEY)
	public List<LabelVO> populateRegisterNonClientCompanyClientLicIssueAuth() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<LicIssueAuthVO> issueAuthVOs = utilityDelegate.getAllLicIssuingAuth();

		for (LicIssueAuthVO authVO : issueAuthVOs) {
			labelVO = getMapper().map(authVO,LabelVO.class);
			labelList.add(labelVO);

		}
		return labelList;
	}
	
	@ModelAttribute(ConstantsAdmin.CLIENT_TYPES_MODEL_KEY)
	public List<LabelVO> populateClientTypesListModel(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.COMPANY);	
		labelVO.setDisplayLabel(getMessageSource().getMessage("label.client.company", null, locale));
		labelList.add(labelVO);

		labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.PERSON);	
		labelVO.setDisplayLabel(getMessageSource().getMessage("label.client.person", null, locale));
		labelList.add(labelVO);

		return labelList;
	}
	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * /client/register/recallpin
	 * 
	 * @see WEB-INF/jsp/client/register/recallpin/form.jsp
	 * @see WEB-INF/jsp/client/register/recallpin/show.jsp
	 */

	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void form(@ModelAttribute(value = ConstantsAdmin.CLIENT_REGISTER_RECALLPIN_MODEL_KEY) ClientRecallPinLogin command) {
	    command.setClientType(ConstantsCommon.COMPANY);
	}

	@RequestMapping(value = "/show.htm", method = RequestMethod.GET)
	public void show() {
	    
	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * /client/register/recallpin/form.jsp , /client/register/recallpin/show.jsp
	 * 
	 * @see #form(ClientPasswordLogin)
	 * @see WEB-INF/jsp/client/register/recallpin/form.jsp
	 *      WEB-INF/jsp/client/register/recallpin/show.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public String find(
			HttpServletRequest request,
			Locale locale,
			SessionStatus status,
			@ModelAttribute(value = ConstantsAdmin.CLIENT_REGISTER_RECALLPIN_MODEL_KEY) @Valid ClientRecallPinLogin clientRecallpinRegister,
			BindingResult errors) {

	    	validateForm(clientRecallpinRegister, errors, locale);
		if (errors.hasErrors()) {
		    	
				for (Object object : errors.getAllErrors()) {
					if (object instanceof FieldError) {
						FieldError fieldError = (FieldError) object;

					}
					
					if (object instanceof ObjectError) {
						ObjectError objectError = (ObjectError) object;

					}
				}

				return ViewUtils.DEFAULT_VIEW;

			} else {
			    	TrakheesIdAndPINVO idAndPINVO = null;
			    	
			    	if(ConstantsCommon.PERSON.equalsIgnoreCase(clientRecallpinRegister.getClientType())){
			    	    idAndPINVO = this.clientRegistrationDelegate.findTrakheesIdAndPinByEmail(clientRecallpinRegister.getStrEmail());
			    	}else if(ConstantsCommon.COMPANY.equalsIgnoreCase(clientRecallpinRegister.getClientType())){
			    	    SearchCriteriaCompanyVO searchCriteriaCompanyVO = new SearchCriteriaCompanyVO();
			    	    getMapper().map(clientRecallpinRegister, searchCriteriaCompanyVO);
			    	    idAndPINVO = this.clientRegistrationDelegate.findTrakheesIdAndPinByLicenseInfo(searchCriteriaCompanyVO);
			    	}
				if(idAndPINVO != null )
				{	
					ClientEmailVO clientEmailVO = new ClientEmailVO();
					
					clientEmailVO.setStrEmailAddress(idAndPINVO.getStrEmail());
					clientEmailVO.setStrEmailSubject(getMessageSource().getMessage("msg.pin.recall.subject", null, locale));
					clientEmailVO.setStrEmailBody(getMessageSource().getMessage("msg.pin.recall.body", new String[] {idAndPINVO.getStrTrakheesID(), idAndPINVO.getStrTrakheesPIN()}, locale));
					
					
					this.clientRegistrationDelegate.recallClientTrakheesID(clientEmailVO);
					return ViewUtils.getRedirect(ViewPath.RECALLPIN, PageType.SHOW);
				}
				else
				{
					if(ConstantsCommon.PERSON.equalsIgnoreCase(clientRecallpinRegister.getClientType())){
						String[] messageArgs = new String[] { getMessageSource().getMessage("label.company.uploaddocuments", null,
								RequestContextUtils.getLocale(request)) };
						errors.reject("error.client.email.not.found", messageArgs, null);
					}else if(ConstantsCommon.COMPANY.equalsIgnoreCase(clientRecallpinRegister.getClientType())){
						String[] messageArgs = new String[] { getMessageSource().getMessage("label.company.uploaddocuments", null,
								RequestContextUtils.getLocale(request)) };
						errors.reject("error.client.license.not.found", messageArgs, null);
					}
				}
				
			}

		
		return ViewUtils.DEFAULT_VIEW;
	}

	/**
	 * validateForm
	 * 
	 * @param clientRecallpinRegister
	 * @param errors
	 * void
	 * @param locale 
	 */
	private void validateForm(ClientRecallPinLogin clientRecallpinRegister,
		BindingResult errors, Locale locale) {
	    if(!ConstantsCommon.PERSON.equalsIgnoreCase(clientRecallpinRegister.getClientType()) && !ConstantsCommon.COMPANY.equalsIgnoreCase(clientRecallpinRegister.getClientType())){
		String[] messageArgs = new String[] { getMessageSource().getMessage("error.invalid.clienttype", null, locale) };
		errors.reject("error.invalid.clienttype", messageArgs, null);
	    }else if(ConstantsCommon.PERSON.equalsIgnoreCase(clientRecallpinRegister.getClientType()) && StringUtils.isBlank(clientRecallpinRegister.getStrEmail())){
		String[] messageArgs = new String[] { getMessageSource().getMessage("error.strEmailAddress", null, locale) };
		errors.reject("error.strEmailAddress", messageArgs, null);
	    }else if(ConstantsCommon.COMPANY.equalsIgnoreCase(clientRecallpinRegister.getClientType()) && StringUtils.isBlank(clientRecallpinRegister.getStrLicenseIssuingAuth())){
		String[] messageArgs = new String[] { getMessageSource().getMessage("error.strLicenseIssuingAuth", null, locale) };
		errors.reject("error.strLicenseIssuingAuth", messageArgs, null);
	    }else if(ConstantsCommon.COMPANY.equalsIgnoreCase(clientRecallpinRegister.getClientType()) && StringUtils.isBlank(clientRecallpinRegister.getStrLicenseNumber())){
		String[] messageArgs = new String[] { getMessageSource().getMessage("error.strLicenseNumber", null, locale) };
		errors.reject("error.strLicenseNumber", messageArgs, null);
	    }
	    
	}

}
